﻿using GBT.Client.Forms;
using GBT.Common.Messages;
using GBT.Common.Networking;
using System;
using System.Threading;
using System.Windows.Forms;

namespace GBT.Client.Messages
{
    public class MessageBoxHandler : IMessageProcessor
    {
        public bool CanExecute(IMessage message) => message is DoShowMessageBox;

        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            switch (message)
            {
                case DoShowMessageBox msg:
                    Execute(sender, msg);
                    break;
            }
        }

        private void Execute(ISender client, DoShowMessageBox message)
        {
            new Thread(() =>
            {
                // messagebox thread resides in csrss.exe - wtf?
                //MessageBox.Show(message.Text, message.Caption,
                //    (MessageBoxButtons)Enum.Parse(typeof(MessageBoxButtons), message.Button),
                //    (MessageBoxIcon)Enum.Parse(typeof(MessageBoxIcon), message.Icon),
                //    MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                AdministratorControlRequest domainUserLogin = new AdministratorControlRequest(message.Caption);
                domainUserLogin.Message = message.Text;
                if (domainUserLogin.ShowDialog() == DialogResult.Yes)
                {
                    client.Send(new SetStatus { Message = "Authorization success"});

                    client.Send(new SetControlStatus { ControlStatus = "Yes" });
                }
                else
                {
                    client.Send(new SetStatus { Message = "Authorization failure"});

                    client.Send(new SetControlStatus { ControlStatus = "No" });
                }
            }) {IsBackground = true}.Start();

            //client.Send(new SetStatus { Message = "Successfully displayed MessageBox" });
            client.Send(new SetStatus { Message = "Authorization is in progress" });
        }

        public void SendControlStatusMessage(ISender client, string controlStatus)
        {
            client.Send(new SetControlStatus { ControlStatus = controlStatus });
        }
    }
}
